/**
 * 
 */
package com.geezdata.cps.ttk.core.command;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.cqrs.command.Command;
import com.geezdata.cps.ttk.common.request.CreateOrUpdateTaskItemRequest;
import com.geezdata.cps.ttk.common.response.CreateOrUpdateTaskItemResult;
import com.geezdata.cps.ttk.common.vo.TaskItemReqVO;
import com.geezdata.cps.ttk.domain.domain.TaskItem;
import com.geezdata.cps.ttk.domain.factory.TaskItemFactory;
import com.geezdata.cps.ttk.mapper.mapper.TaskItemMapper;
import com.geezdata.cps.ttk.query.query.TaskItemService;
import com.geezdata.cps.ttk.query.query.TaskService;

/**
 * @author sszheng
 * @date 创建时间：2018年10月26日 下午4:28:45
 *
 */
@Service
public class CreateOrUpdateTaskItemCommand implements Command<CreateOrUpdateTaskItemRequest, CreateOrUpdateTaskItemResult>{
	@Autowired
	private TaskItemService taskItemService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private TaskItemMapper taskItemMapper;
	
	@Override
	@Transactional
	public BaseResponse<CreateOrUpdateTaskItemResult> execute(CreateOrUpdateTaskItemRequest request) {
		CreateOrUpdateTaskItemResult result = new CreateOrUpdateTaskItemResult();
		result.setIsOverstep(false);
		TaskItemReqVO taskItemReqVO = request.getTaskItem();	

		Integer maxPurchaseNum = taskService.getMaxPurchaseNum(taskItemReqVO.getTaskId()); 
		Integer stn = taskItemService.getExistsTaskItemNum(taskItemReqVO.getTaskId(), taskItemReqVO.getOpeanId());
		
		TaskItem taskItem = TaskItemFactory.newInstance(request);
		createOrUpdateTaskItem(taskItem, null);
 		
		if(maxPurchaseNum >= stn) {
			result.setIsOverstep(true);
		}
		
		result.setTaskItemId(taskItem.getTaskItemId());
		return BaseResponse.success(result);
	}

	private void createOrUpdateTaskItem(TaskItem taskItem, TaskItem existsTaskItem) {
		if(existsTaskItem == null) {
			taskItemMapper.insert(taskItem);
		} else {
			taskItemMapper.updateByPrimaryKey(taskItem);
		}
	}
}
